﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace Tool
{
    public partial class Form1 : Form
    {
        private string siteUrl = "http://ws-hwenlong-02:19766/sites/eNPI";
        private string templatePath = @"E:\eNPI\template\";
        private string outputPath = @"E:\eNPI\info\";
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            using (SPSite oSite = new SPSite(siteUrl))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPListCollection lists = oWeb.Lists;
                    foreach (SPList list in lists)
                    {
                        string listName = list.Title;
                        this.comboBox1.Items.Add(listName);
                    }
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.checkedListBox1.Items.Clear();
            string listName = this.comboBox1.Text;
            using (SPSite oSite = new SPSite(siteUrl))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPList oList = oWeb.Lists[listName];
                    SPFieldCollection fields = oList.Fields;
                    foreach (SPField f in fields)
                    {
                        string internalName = f.InternalName;
                        string type = f.TypeAsString;

                        string title = f.Title;


                        this.checkedListBox1.Items.Add(internalName + "," + type + "," + title);
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.CheckedListBox.CheckedItemCollection checkedItems = this.checkedListBox1.CheckedItems;
            string className = comboBox1.Text;
            GenerateBusinessEntityClassFile(templatePath, outputPath, "BusinessEntityTemplate.txt", className + ".cs", className, checkedItems);
            GenerateFieldsConstantsClassFile(templatePath, outputPath, "FieldsConstantsTemplate.txt", className + "FieldIds.cs", className + "FieldIds", checkedItems);
            GenerateRepositoryClassFile("ListNameConstants." + className, templatePath, outputPath, "RepositoryTemplate.txt", className + "Repository.cs", className, checkedItems);
        }

        private void GenerateBusinessEntityClassFile(string templatePath, string outputPath, string templateName, string fileName, string className, System.Windows.Forms.CheckedListBox.CheckedItemCollection checkedItems)
        {
            System.Text.StringBuilder sb = new StringBuilder();
            sb.Append(Environment.NewLine);
            foreach (object item in checkedItems)
            {
                string value = item.ToString();
                string[] array = value.Split(',');
                string internalName = array[0];
                string type = array[1];
             //   string entry = "public " + "object" + " " + internalName + " { get; set; }" + "//" + type + "";
                string entry = getAttriInfos(array) +"{set;get;}";
                sb.Append(entry);
                sb.Append(Environment.NewLine);
            }
            string txtTemplate = ReadTemplateFile(templatePath, templateName);
            string txt = txtTemplate;
            txt = txt.Replace("[ClassName]", className);
            txt = txt.Replace("[Code]", sb.ToString());
            CreateFileAndThenWriteToFile(outputPath, fileName, txt);
        }

        public string getAttriInfos(string[] array)
        {
            string internalName = array[0];
            string type = array[1];
            string Title = array[2].Replace(" ", "").Replace("&","_").Replace("-","_");
            string myAttribute = @"public {0} {1} ";
            if (type == "Text" || type == "Note" || type == "Choice")
            {
                return string.Format(myAttribute, "string", Title);
            }
            else if (type == "User")
            {
                return string.Format(myAttribute, "SPFieldUserValue", Title);
            }
            else if (type == "DateTime")
            {
                return string.Format(myAttribute, "DateTime?", Title);
            }
            else if (type == "Counter")
            {
                return string.Format(myAttribute, "int", Title);
            }
            else if (type == "UserMulti")
            {
                return string.Format(myAttribute, "SPFieldUserValueCollection", Title);
            }
            else if (type == "Lookup")
            {
                return string.Format(myAttribute, "SPFieldLookupValue", Title);
            }
            else if (type == "Integer")
            {
                return string.Format(myAttribute, "int?", Title);
            }

            else if (type == "Boolean")
            {
                return string.Format(myAttribute, "bool?", Title);
            }

            return string.Format(myAttribute, "object", Title);

        }


        private void GenerateFieldsConstantsClassFile(string templatePath, string outputPath, string templateName, string fileName, string className, System.Windows.Forms.CheckedListBox.CheckedItemCollection checkedItems)
        {
            System.Text.StringBuilder sb = new StringBuilder();
            sb.Append(Environment.NewLine);
            foreach (object item in checkedItems)
            {
                string value = item.ToString();
                string[] array = value.Split(',');

                string internalName = array[0];

                string title = array[2];


                string entry = string.Format("public static readonly string {0} = \"{1}\";", title.Replace(" ","").Replace("/","_").Replace("&","_"), internalName);
                sb.Append(entry);
                sb.Append(Environment.NewLine);
            }
            string txtTemplate = ReadTemplateFile(templatePath, templateName);
            string txt = txtTemplate;
            txt = txt.Replace("[ClassName]", className);
            txt = txt.Replace("[Code]", sb.ToString());
            CreateFileAndThenWriteToFile(outputPath, fileName, txt);
        }

        private void GenerateRepositoryClassFile(string listId, string templatePath, string outputPath, string templateName, string fileName, string entityClassName, System.Windows.Forms.CheckedListBox.CheckedItemCollection checkedItems)
        {
            System.Text.StringBuilder sb = new StringBuilder();
            sb.Append(Environment.NewLine);
            foreach (object item in checkedItems)
            {
                string value = item.ToString();
                string[] array = value.Split(',');
                string internalName = array[0];
                string entry = string.Format("listItemFieldMapper.AddMapping(dict[{0}FieldIds.{1}],{0}FieldIds.{2});", entityClassName, internalName, internalName);
                sb.Append(entry);
                sb.Append(Environment.NewLine);
            }
            string txtTemplate = ReadTemplateFile(templatePath, templateName);
            string txt = txtTemplate;
            txt = txt.Replace("[EntityClassName]", entityClassName);
            txt = txt.Replace("[Code]", sb.ToString());
            txt = txt.Replace("[ListId]", listId);
            CreateFileAndThenWriteToFile(outputPath, fileName, txt);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string fileName = "ListNameConstants.cs";
            string templateName = "ListNameConstantsTemplate.txt";
            System.Text.StringBuilder sb = new StringBuilder();
            sb.Append(Environment.NewLine);
            using (SPSite oSite = new SPSite(siteUrl))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPListCollection lists = oWeb.Lists;
                    foreach (SPList list in lists)
                    {
                        string listNameIncludeSpace = list.Title;
                        System.Text.StringBuilder sbListName = new System.Text.StringBuilder();
                        char[] chars = listNameIncludeSpace.ToCharArray();
                        foreach (char c in chars)
                        {
                            if (c != ' ')
                            {
                                sbListName.Append(c);
                            }
                        }
                        string listNameExcludeSpace = sbListName.ToString();
                        string listId = list.ID.ToString();
                        string entry = string.Format("public static readonly string {0} = \"{1}\";", listNameExcludeSpace, listId);
                        sb.Append(entry);
                        sb.Append(Environment.NewLine);
                    }
                }
            }
            string txtTemplate = ReadTemplateFile(templatePath, templateName);
            string txt = txtTemplate;
            txt = txt.Replace("[Code]", sb.ToString());
            CreateFileAndThenWriteToFile(outputPath, fileName, txt);
        }

        private string ReadTemplateFile(string templatePath, string templateName)
        {
            string s = string.Empty;
            using (System.IO.StreamReader reader = new System.IO.StreamReader("" + templatePath + templateName + ""))
            {
                s = reader.ReadToEnd();
            }
            return s;
        }

        private void CreateFileAndThenWriteToFile(string outputPath, string fileName, string txt)
        {
            using (System.IO.File.Create("" + outputPath + fileName + ""))
            {

            }
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter("" + outputPath + fileName + ""))
            {
                writer.Write(txt);
            }
        }

        private void SelectAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
            {
                this.checkedListBox1.SetItemChecked(i, true);
            }

        }
    }
}
